package com.aa.activity;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import com.aa.Common;
import com.aa.R;
import com.aa.http.HttpOperation;
import com.aa.util.MessageItem;
import com.aa.util.SMS;
import com.aa.util.SMSObserver;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity implements OnClickListener{

	private final String mUrl = "http://121.9.64.196:8087/AAproject/api/mobile.php";
	private Button mbtnBack;
	private TextView mtvTitleCenter;
	private EditText metPhoneNumber;
	private EditText metPassword;
	private EditText metEnsurePassword;
	private EditText metCode;
	private Button mbtnGetCode;
	private Button mbtnOk;
	private String TAG = "RegisterActivity";
	private String mPhoneNumber;
	private String mPassword;
	private int mSendSMSErrorCount = 0;
	private String mCode ; 
	private boolean isRegisetSMS = false;
	private boolean sendCodeSuccessed = false;
	private ContentObserver mObserver;
	private ProgressDialog mProgressDialog;
	private Handler mHandler;
	private String mRetureErrMSG = "";
	private BroadcastReceiver smsRet = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "getResultCode = " + getResultCode());
		switch (getResultCode()) {
		case -1:
			String str = getString(R.string.app_commend_10);
			Toast.makeText(RegisterActivity.this, str, 3000).show();
			
			break;

		default:
			mbtnGetCode.setText(R.string.findpassword_6);
			break;
		}
			
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.register);
		initView();
		
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {				
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					Toast.makeText(RegisterActivity.this, mRetureErrMSG, 3000).show();
					break;
				case 1:
					Toast.makeText(RegisterActivity.this, R.string.app_register_succeful, 3000).show();
					finish();
					break;
				case 2:
					Toast.makeText(RegisterActivity.this, R.string.http_get_fail, 3000).show();
					break;
				default:
					break;
				}
			}
			
		};
	}

	private void initView(){
		mbtnBack = (Button)findViewById(R.id.btn_title_back);
		mbtnBack.setOnClickListener(this);
		mtvTitleCenter = (TextView)findViewById(R.id.tv_title_center);
		mtvTitleCenter.setText(R.string.app_register);
		mtvTitleCenter.setVisibility(View.VISIBLE);
		metCode = (EditText)findViewById(R.id.et_code);
		//metCode.setFocusable(false);
		metPassword = (EditText)findViewById(R.id.et_register_password);
		metEnsurePassword = (EditText)findViewById(R.id.et_register_password2);
		metPhoneNumber = (EditText)findViewById(R.id.et_register_phoneNumber);
		mbtnGetCode = (Button)findViewById(R.id.btn_get_code);
		mbtnGetCode.setOnClickListener(this);
		mbtnOk = (Button)findViewById(R.id.btn_ok);
		mbtnOk.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_title_back:
			finish();
			break;
		case R.id.btn_get_code:
			mPhoneNumber = metPhoneNumber.getText().toString().trim();
			if (mPhoneNumber == null || mPhoneNumber.length() != 11) {
				Toast.makeText(RegisterActivity.this, R.string.app_right_phoneNumber, 3000).show();
				return;
			}
			mCode = Common.randomCode();
			ContentResolver _ContentResolver = getContentResolver();
			mObserver = new SMSObserver(_ContentResolver, new FPSMSHandler(this),mPhoneNumber,mCode);
			_ContentResolver.registerContentObserver(SMS.CONTENT_URI, true,mObserver);
			sendTip();
			break;
		case R.id.btn_ok:
			
			register();
			break;
		default:
			break;
		}
		
	}
	
	private void register(){
		mPhoneNumber = metPhoneNumber.getText().toString().trim();
		if (mPhoneNumber == null || mPhoneNumber.length() != 11) {
			Toast.makeText(RegisterActivity.this, R.string.app_right_phoneNumber, 3000).show();
			return;
		}
		mPassword = metPassword.getText().toString().trim();
		if (mPassword.length() == 0) {
			Toast.makeText(RegisterActivity.this, R.string.app_null_password, 3000).show();
			return;
		}
		
		String _Password = metEnsurePassword.getText().toString().trim();
		if (!mPassword.equals(_Password)) {
			Toast.makeText(RegisterActivity.this, R.string.app_password_no_matcher,3000).show();
			metPassword.setText("");
			metEnsurePassword.setText("");
			return;
		}
		
		mCode = metCode.getText().toString();
		if (mCode.length() == 0) {
			Toast.makeText(RegisterActivity.this, R.string.app_please_get_code, 3000).show();
			return;
		}
		
		sumbitRegister(mPhoneNumber, mPassword);
	}
	
	private void sendTip(){
		String tip = getString(R.string.app_tip);
	    String ok = getString(R.string.app_ok);
	    String cancel = getString(R.string.app_cancel);
	    String sms = getString(R.string.app_tip_sms);
	    
	    if (mSendSMSErrorCount == 0) {
			new AlertDialog.Builder(this).setTitle(tip)
			.setMessage(sms)
			.setPositiveButton(ok, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					sendSMS(mPhoneNumber, mCode);
					dialog.dismiss();
					
				}
			}).setNegativeButton(cancel, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					
				}
			}).show();
			return;
		}
	    sendSMSFromSystem(mPhoneNumber, mCode);	    
	}
	
	private void sendSMS(String pPhoneNumber, String pCode){
		if (pPhoneNumber == null || pPhoneNumber.length() == 0 || pCode == null || pCode.length() == 0) {
			return;
		}
		

		SmsManager _SmsManager = SmsManager.getDefault();
		Intent _Intent = new Intent("SENT_SMS_ACTION");
		PendingIntent _PendingIntent = PendingIntent.getBroadcast(this, 0, _Intent, 0);
		
		Intent _Intent2 = new Intent("DELIVERED_SMS_ACTION");
		PendingIntent _PendingIntent2 = PendingIntent.getBroadcast(this, 0, _Intent2, 0);
		
		 registerReceiver(this.smsRet, new IntentFilter("SENT_SMS_ACTION"));
		 isRegisetSMS = true;
		 Iterator _Iterator;
		 
		 if (pCode.length() > 70) {
			_Iterator = _SmsManager.divideMessage(pCode).iterator();
			while(true){
				if (!_Iterator.hasNext()) {
					return;
				}
				_SmsManager.sendTextMessage(pPhoneNumber, null, (String)_Iterator.next(), _PendingIntent, _PendingIntent2);
			}
		}else {
			_SmsManager.sendTextMessage(pPhoneNumber, null, pCode, _PendingIntent, _PendingIntent2);
		}
	}
	
	  private void sendSMSFromSystem(String pPhoneNumber, String pCode){
	    Intent _Intent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:" + pPhoneNumber));
	    _Intent.putExtra("sms_body", pCode);
	    startActivityForResult(_Intent, 1);
	  }
	  
	  class FPSMSHandler extends Handler{
		  
	    public static final String TAG = "FPSMSHandler";
	    private Context mContext;

	    public FPSMSHandler(Context pContext){
	      
	      mContext = pContext;
	    }

	    public void handleMessage(Message pMessage){
	    	
	      MessageItem _MessageItem = (MessageItem)pMessage.obj;
	      Uri localUri = ContentUris.withAppendedId(SMS.CONTENT_URI, _MessageItem.getId());
	      try
	      {
	        mContext.getContentResolver().delete(localUri, null, null);
	        metCode.setText(mCode);
	        sendCodeSuccessed = true;
	        return;
	      }
	      catch (Exception localException)
	      {
	        localException.printStackTrace();
	      }
	    }
	  }

	  
		private void sumbitRegister(String pNumber, String pPassword){
			
				mProgressDialog = ProgressDialog.show(this, getString(R.string.app_progress_title), 
						getString(R.string.app_progress_tip),true,false);
				mProgressDialog.setCancelable(true);
			
			
			final JSONObject _SendJson = new JSONObject();
			JSONObject _BodyJson = new JSONObject();
			JSONObject _HeadJson = new JSONObject();
			try {
				_HeadJson.put("v", "1.0.0");
				_HeadJson.put("time", System.currentTimeMillis());
				_HeadJson.put("cmd", 7);
				_HeadJson.put("mac", Common.iMac);
				_HeadJson.put("agent", Common.iAgentId);
										
				_BodyJson.put("pwd", pPassword);
				_BodyJson.put("pnumber", pNumber);
			
				
				_SendJson.put("head", _HeadJson);
				_SendJson.put("body", _BodyJson);
				Log.i(TAG, "sendJson = " + _SendJson);
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					
					String _Result = HttpOperation.postRequestJSONFormat(mUrl, _SendJson.toString());
					mProgressDialog.dismiss();
					Log.i(TAG, "return _Result = " + _Result);
					if ( _Result == null || _Result.length() == 0 || _Result.equals(Common.iConnectOutTime)) {
						mHandler.sendEmptyMessage(2);
						return;
					}
					
						
						try {
							JSONObject _JsonObject = new JSONObject(_Result);
							
							JSONObject _Body = _JsonObject.getJSONObject("body");
							
							if(_Body.getInt("rcode") == 1) {
								mHandler.sendEmptyMessage(1);
							}else {
								mRetureErrMSG = _Body.getString("msg");
								mHandler.sendEmptyMessage(0);
							}
						} catch (JSONException e) {						
							e.printStackTrace();
						}
					}
					
				
			}).start();
		}
	  
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		 if ((smsRet != null) && (isRegisetSMS)){
			 
		      unregisterReceiver(smsRet);
		      isRegisetSMS = false;
		     
		    }
		 if (mObserver != null) {
			 getContentResolver().unregisterContentObserver(mObserver);
		}
		   
	}
	  
	  
}
